import React from 'react';
import { IWidget, IWidgetGroup } from '../../common';
import { useAutorun } from '../../../react-hooks/react-hooks';

import styles from './resize.module.less';

export enum ResizeDirection {
  vertical,
  horizontal,
}

export interface IResizeViewProps {
  direction: ResizeDirection;
  useFlex: boolean;
  shadow: boolean;
  group: IWidgetGroup;
  draw: (widget: IWidget) => JSX.Element;
}

interface ResizePanelItemProps {
  widget: IWidget;
  dynamic: any;
  draw: (widget: IWidget) => JSX.Element;
  handleRemoveWidget: (id: string) => void;
  widgetsLength: number;
}

const ResizePanelItem: React.FC<ResizePanelItemProps> = ({
                                                           widget,
                                                           dynamic,
                                                           draw,
                                                           handleRemoveWidget,
                                                           widgetsLength,
                                                         }) => {
  const _dynamic = useAutorun(dynamic);

  return (
    <div key={widget.id} style={{ width: `${_dynamic}%` }}>
      {draw(widget)}
      {widgetsLength > 1 && (
        <div
          className={styles.closeBtn}
          onClick={() => {
            handleRemoveWidget(widget.id);
          }}
        />
      )}
    </div>
  );
};

const ResizeView: React.FC<IResizeViewProps> = (props) => {
  const { group, shadow } = props;
  const widgets = useAutorun(group.widgets);

  const [event, setEvent] = React.useState(false);
  const [wholeWidth, setWholeWidth] = React.useState(Infinity);
  const whole = React.useRef<HTMLDivElement | null>(null);

  React.useEffect(() => {
    if (whole.current && whole.current.clientHeight !== wholeWidth) {
      setWholeWidth(whole.current.clientWidth);
    }
  });

  const handleRemoveWidget = React.useCallback((widgetId: string) => {
  }, []);

  return (
    <div className={styles.resizeWrapper} ref={whole}>
      <div
        style={{ pointerEvents: !event ? 'all' : 'none' }}
        className={styles.resizePanel}
      >
        {widgets &&
          widgets.map((widget) => (
            <ResizePanelItem
              key={widget.id}
              widget={widget}
              dynamic={shadow ? widget.dynamic : widget.shadowDynamic}
              draw={props.draw}
              handleRemoveWidget={handleRemoveWidget}
              widgetsLength={widgets.length}
            />
          ))}
      </div>
    </div>
  );
};

export default ResizeView;
